<template>
  <div class="header">
    <el-input
      style="width: 300px"
      v-model="ipAddress"
      placeholder="输入CIDR地址(IPv4)  例如:172.18.0.1/16"
    ></el-input>
    <el-button @click="convertIPAddress">点击转换</el-button>
  </div>
  <div class="nya-copy" v-clipboard:copy="binaryIPAddress">
    <span>二进制：{{ binaryIPAddress }}</span>
    <i class="iconfont icon-fuzhi" @click="handleCopy" title="点击复制结果"></i>
  </div>
  <div class="nya-copy" v-clipboard:copy="decIPAddress">
    <span>十进制：{{ decIPAddress }}</span>
    <i class="iconfont icon-fuzhi" @click="handleCopy" title="点击复制结果"></i>
  </div>
  <div class="nya-copy" v-clipboard:copy="hexIPAddress">
    <span>十六进制：{{ hexIPAddress }}</span>
    <i class="iconfont icon-fuzhi" @click="handleCopy" title="点击复制结果"></i>
  </div>
</template>

<script setup>
import { reactive, toRefs } from "vue";

const data = reactive({
  ipAddress: "",
  binaryIPAddress: "",
  hexIPAddress: "",
  decIPAddress: "",
});

const { ipAddress, binaryIPAddress, hexIPAddress, decIPAddress } = toRefs(data);

//进行ip转换处理
const convertIPAddress = () => {
  let ipAddressArray = data.ipAddress.split(".");
  let binaryIPAddress = "";
  let hexIPAddress = "";
  let ipAddress = data.ipAddress;
  for (let i = 0; i < ipAddressArray.length; i++) {
    let binary = parseInt(ipAddressArray[i]).toString(2);
    let hex = parseInt(ipAddressArray[i]).toString(16);
    binaryIPAddress += binary + ".";
    hexIPAddress += hex + ".";
  }
  data.binaryIPAddress = binaryIPAddress.slice(0, -1);
  data.hexIPAddress = hexIPAddress.slice(0, -1);
  data.decIPAddress = ipAddress
    .match(/\d+/g)
    .map(Number)
    .reduce((a, b) => a * 256 + b);
};

//复制事件
const handleCopy = () => {
  if (
    data.binaryIPAddress === "" ||
    data.hexIPAddress === "" ||
    data.binaryIPAddress === ""
  )
    return ElMessage({
      showClose: true,
      message: "不能复制空内容！",
      type: "error",
    });
  ElMessage({
    showClose: true,
    message: "复制成功",
    type: "success",
  });
};
</script>

<style lang="less" scoped>
.header,
.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
h3 {
  margin-bottom: 5px;
}
.nya-copy {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  background-color: aliceblue;
  height: 35px;
  //   width: 440px;
  line-height: 35px;
  min-width: 200px;
  margin: 15px 0px 15px 0px;
  .iconfont {
    margin-right: 8px;
  }
  span {
    margin-left: 5px;
  }
}
</style>
